import {request} from "../../request/index.js"

// pages/goods_detail/main.js
Page({
  data: {
    goodsObj:{}
  },
  GoodsInfo:{},
  onLoad: function (options) {
    const {goods_id} = options
    this.getGoodsDetail(goods_id)
  },
  //获取商品详情数据
  async getGoodsDetail(goods_id){
    const res = await request({url:"/goods/detail",data:{goods_id}})
    let data = res.data.message
    this.GoodsInfo = data
    this.setData({
      goodsObj:{
        goods_name:data.goods_name,
        goods_price:data.goods_price,
        goods_introduce:data.goods_introduce.replace(/\.webp/g,".jpg"),
        pics:data.pics,
      }
    })
  },
  //点击轮播图放大预览
  handlePreviewImage(e){
    const urls = this.data.goodsObj.pics.map((v,i,arr)=>v.pics_mid)
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current, //打开第几张的链接
      urls
    });
  },
  // 加入购物车
  handleCartAdd(){
    //获取缓存
    let cart = wx.getStorageSync("cart") || [];
    // 判断是否已经存在
    let index = cart.findIndex(v=>v.goods_id == this.GoodsInfo.goods_id)
    
    if(index == -1){
      //不存在
      this.GoodsInfo.num = 1
      this.GoodsInfo.checked = true
      cart.push(this.GoodsInfo)
    }else{
      //存在
      cart[index].num++
    }
      
    //重新添加回缓存中
    wx.setStorageSync("cart",cart);
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      //防止用户疯狂点击这个按钮
        mask: true, //1.5秒后才能在点击
    });
      
      
  }

})